package com.shanliao.version;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.mvc.condition.RequestCondition;

import com.shanliao.util.VersionUtil;

public class ApiVesrsionCondition implements RequestCondition<ApiVesrsionCondition> {

	private String apiVersion;

	public ApiVesrsionCondition(String apiVersion) {
		this.apiVersion = apiVersion;
	}

	@Override
	public ApiVesrsionCondition combine(ApiVesrsionCondition other) {
		// 采用最后定义优先原则，则方法上的定义覆盖类上面的定义
		return new ApiVesrsionCondition(other.getApiVersion());
	}

	@Override
	public ApiVesrsionCondition getMatchingCondition(HttpServletRequest request) {
		String version = request.getHeader("version");
		if (StringUtils.isNotBlank(version)) {
			version = request.getParameter("version");
		}
		if (StringUtils.isNotBlank(version)) {
			// 如果请求的版本号大于配置版本号， 则满足
			if (VersionUtil.of(version).complete().gt(apiVersion)) {
				return this;
			}
		}

		return null;
	}

	/**
	 * 对两个RequestCondition对象进行比较，这里主要是如果存在两个注册的一样的Mapping，
	 * 那么就会对这两个Mapping进行排序，以判断哪个Mapping更适合处理当前request请求
	 *
	 * @param other
	 * @param request
	 * @return 返回-1,0,1
	 */
	@Override
	public int compareTo(ApiVesrsionCondition other, HttpServletRequest request) {
		// 优先匹配最新的版本号
		return VersionUtil.of(other.getApiVersion()).complete().gt(this.apiVersion) ? 1 : -1;
	}

	public String getApiVersion() {
		return apiVersion;
	}

}